<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <div class="logo">
          <el-icon><Monitor /></el-icon>
          <h1>用户注册</h1>
        </div>
        <p class="subtitle">创建您的工单管理账户</p>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            size="large"
            :prefix-icon="Message"
            clearable
          />
        </el-form-item>

        <el-form-item prop="fullName">
          <el-input
            v-model="registerForm.fullName"
            placeholder="请输入真实姓名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleRegister"
          />
        </el-form-item>

        <el-form-item prop="role">
          <el-select
            v-model="registerForm.role"
            placeholder="请选择用户角色"
            size="large"
            style="width: 100%"
          >
            <el-option label="客户" value="customer" />
            <el-option label="客服" value="agent" />
          </el-select>
        </el-form-item>

        <el-form-item prop="agree">
          <el-checkbox v-model="registerForm.agree">
            我已阅读并同意
            <el-link type="primary" @click="showTerms">《用户协议》</el-link>
            和
            <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-button"
            :loading="loading"
            @click="handleRegister"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button
            type="default"
            size="large"
            class="back-button"
            @click="goToLogin"
          >
            返回登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, Monitor, Message } from '@element-plus/icons-vue'

export default {
  name: 'Register',
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()
    const registerFormRef = ref()
    const loading = ref(false)

    const registerForm = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      fullName: '', // 添加真实姓名字段
      role: 'customer',
      agree: false
    })

    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    const registerRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      fullName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '真实姓名长度在 2 到 50 个字符', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z\s]+$/, message: '真实姓名只能包含中文、英文和空格', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
      ],
      agree: [
        { required: true, message: '请同意用户协议和隐私政策', trigger: 'change' }
      ]
    }

    const handleRegister = async () => {
      if (!registerFormRef.value) return

      try {
        // 前端表单验证
        console.log('🔍 开始前端表单验证')
        await registerFormRef.value.validate()
        console.log('✅ 前端表单验证通过')

        // 额外的业务逻辑验证
        if (!validateFormData()) {
          return
        }

        loading.value = true
        console.log('🔍 准备发送注册请求，表单数据:', registerForm)

        const result = await authStore.register({
          username: registerForm.username,
          email: registerForm.email,
          password: registerForm.password,
          confirmPassword: registerForm.confirmPassword,
          fullName: registerForm.fullName,
          role: registerForm.role
        })

        console.log('🔍 注册结果:', result)

        if (result.success) {
          ElMessage.success(result.message || '注册成功')
          // 注册成功后跳转到登录页面
          router.push('/login')
        } else {
          ElMessage.error(result.message || '注册失败')
        }
      } catch (error) {
        console.error('❌ 注册处理错误:', error)
        
        // 处理不同类型的错误
        if (error.status) {
          // HTTP错误
          ElMessage.error(`注册失败: ${error.message}`)
        } else if (error.message && error.message.includes('验证')) {
          // 表单验证错误
          ElMessage.warning(error.message)
        } else {
          // 其他错误
          ElMessage.error('注册失败，请检查输入信息')
        }
      } finally {
        loading.value = false
      }
    }

    // 额外的表单数据验证
    const validateFormData = () => {
      console.log('🔍 开始额外验证')
      
      // 检查密码强度
      if (registerForm.password.length < 6) {
        ElMessage.error('密码长度至少6位')
        return false
      }
      
      if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(registerForm.password)) {
        ElMessage.error('密码必须包含字母和数字')
        return false
      }
      
      // 检查密码确认
      if (registerForm.password !== registerForm.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return false
      }
      
      // 检查邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(registerForm.email)) {
        ElMessage.error('请输入正确的邮箱格式')
        return false
      }
      
      // 检查用户名格式
      if (!/^[a-zA-Z0-9_]+$/.test(registerForm.username)) {
        ElMessage.error('用户名只能包含字母、数字和下划线')
        return false
      }
      
      // 检查真实姓名格式
      if (!/^[\u4e00-\u9fa5a-zA-Z\s]+$/.test(registerForm.fullName)) {
        ElMessage.error('真实姓名只能包含中文、英文和空格')
        return false
      }
      
      console.log('✅ 额外验证通过')
      return true
    }

    const goToLogin = () => {
      router.push('/login')
    }

    const showTerms = () => {
      ElMessageBox.alert('用户协议内容...', '用户协议', {
        confirmButtonText: '确定'
      })
    }

    const showPrivacy = () => {
      ElMessageBox.alert('隐私政策内容...', '隐私政策', {
        confirmButtonText: '确定'
      })
    }

    return {
      registerFormRef,
      registerForm,
      registerRules,
      loading,
      handleRegister,
      goToLogin,
      showTerms,
      showPrivacy,
      User,
      Lock,
      Monitor,
      Message
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 450px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 10px;
}

.logo .el-icon {
  font-size: 32px;
  color: #667eea;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #1a202c;
}

.subtitle {
  margin: 0;
  color: #718096;
  font-size: 14px;
}

.register-form {
  margin-bottom: 20px;
}

.register-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.back-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.9);
  border: 2px solid #667eea;
  color: #667eea;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-card {
    padding: 30px 20px;
  }
  
  .logo h1 {
    font-size: 20px;
  }
}
</style>
